package com.xp.tinyurl.service.thirdprovider.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.TypeReference;
import com.xp.tinyurl.common.utils.OkHttp3Utils;
import com.xp.tinyurl.service.thirdprovider.ShorterUrlService;
import com.xp.tinyurl.service.thirdprovider.vo.SinaURLQueryResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SinaShortService implements ShorterUrlService {
    private static final Logger logger = LoggerFactory.getLogger(SinaShortService.class);

    /**
     * 由于V2版本的接口没有申请access token，暂时无法使用
     */
    private static final String SINA_SHORT_URL_API_URL_V2 = "http://api.weibo.com/2/short_url/shorten.json";

    private static final String SINA_ACCESS_TOKEN = "";

    private static final String SINA_SHORT_URL_API_URL_V1 = "http://api.t.sina.com.cn/short_url/shorten.json";

    private static final String APPKEY = "2815391962";

    @Override
    public String shorter(String longUrl) {
        String shortUrl = null;
        Map<String, String> paramMap = new HashMap<>(2);
        paramMap.put("source", APPKEY);
        paramMap.put("url_long", longUrl);
        try {
            String result = OkHttp3Utils.get(SINA_SHORT_URL_API_URL_V1, paramMap);
            List<SinaURLQueryResult> voList = null;
            try {
                voList = JSON.parseObject(result, new TypeReference<List<SinaURLQueryResult>>() {
                });
                shortUrl = voList.get(0).getUrl_short();
                logger.info("Sina short url: {}", shortUrl);
            } catch (JSONException e) {
                logger.error(result);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return shortUrl;
    }

}
